class QuestionVersion
  include Mongoid::Document
  include Mongoid::Timestamps::Created

  belongs_to :author, class_name: 'User', inverse_of: :question_versions
  belongs_to :question

  belongs_to :question_type

  belongs_to :remark

  field :data, type: Array, default: []

  validate :validate_with_question_type

  has_one :vote, dependent: :destroy, autobuild: true
  
  def section
    if !self.question.nil?
      self.question.question_list.section
    elsif !self.remark.nil?
      self.remark.topic.get_question_list.section
    end
  end

  def data_collection
    data = self.data
    def data.metaclass
      class << self; self; end
    end
    self.question_type.question_fields.input.each do |i|
      data.metaclass.send(:define_method, i.position.to_s.to_sym) do
        data[i.position]
      end
    end
    data
  end

  def data_collection_was
    data = self.data_was
    def data.metaclass
      class << self; self; end
    end
    self.question_type.question_fields.input.each do |i|
      data.metaclass.send(:define_method, i.position.to_s.to_sym) do
        data[i.position]
      end
    end
    data
  end

  def update_data_array(params_data_array)
    params_data_array.each do |i,j|
      self.data[i.to_i] = j
    end
    true
  end

  def update_from_params(param, save)
    self.question_type = QuestionType.find(param[:question_type_id])
    self.update_data_array(param[:data_array])
    if save
      self.save
    end
  end

  def self.create_from_params(param, save)
    qv = QuestionVersion.new
    qv.update_from_params(param, save)
    qv
  end

  def clone_without_relations
    qv = self.clone
    qv.question = nil
    qv.remark = nil
    qv.author = nil
    qv
  end

private
  def validate_with_question_type
    def self.metaclass
      class << self; self; end
    end
    error_texts = {}
    self.question_type.question_fields.input.each do |f|
      self.metaclass.send(:define_method, f.name.to_sym) do
        'Yooo' #TODO what the fuck is this
      end
      f.validate_field(data[f.position], error_texts)
    end
    error_texts.each do |name, text|
      errors.add(name.to_sym, text)
    end
  end

end
